//
//  WgtRcdViewCtrl.m
//  AccuroFit
//
//  Created by Yongfeng Li on 9/10/15.
//  Copyright (c) 2015 Nci Technology Inc. All rights reserved.
//


#import <AudioToolbox/AudioServices.h>
#import "AppDelegate.h"
#import "UIGraphView.h"
#import "WgtRcdViewCtrl.h"
#import "N_WgtData.h"
#import "N_FatData.h"
#import "UIView+Extension.h"
#define DefaultColor [UIColor colorWithRed:0.09 green:0.55 blue:0.73 alpha:1.00]
#define CustomColor  [UIColor blackColor];

#define LineH 1.0
#define LineA 0.7
#define LineColor [UIColor grayColor]
@interface WgtRcdViewCtrl ()

@end

@implementation WgtRcdViewCtrl {
  UILabel* _lblMsg;
  
  UIView* _ivhLine1;
  UIView* _ivvLinet;
  UIView* _ivhLine2;
    
  UILabel* _lblWgtTip;
  UILabel* _lblGoalTip;
    
  UILabel* _lblWgtLast;
  UILabel* _lblWgtUnit;
    
  UILabel* _lblGoalWgt;
  UILabel* _lblGoalUnit;
    
  UIGraphView* _gViewWgt;
  UIGraphView* _gViewFat;
    
  UILabel* _lblDatRngTip;
  UISegmentedControl* _scDateRng;
    
  UIView* _ivhLineb;
  UIView* _ivvLineb1;
  UIView* _ivvLineb2;
  UIView* _ivvLineb3;
    
  UILabel* _lblWgtLstTip[4];
  UILabel* _lblWgtLstVal[4];
  UILabel* _lblWgtLstUn[4];
    
    
  NSMutableArray* _pWgtData;
  NSMutableArray* _pFatData;
    
  NSMutableArray* _values;
  NSDate* _lastDatePos;
    
  NSInteger _nDtRngIdx;
  NSDate* _dtFr;
  NSDate* _dtTo;
    
  BOOL _bShowWgt;
  CGPoint _ptViewWgt;
  CGPoint _ptViewFat;
  
  //sync with svr
  UIButton* _btnSyncData;
  UIProgressView* _progView;
  UIActivityIndicatorView* _actView;
  
  NSURLSession* _netSession;
  //NSMutableDictionary* _dicSyncData;
  
  NSUInteger _nSyncPos;
  NSUInteger _nSyncToatalPack;
  NSUInteger _nSyncCurrentPack;
  
  BOOL _bSyncGetWgtReqst;
  BOOL _bSyncGetNotNeed;
  BOOL _bMadeRcdMark;
  BOOL _bSyncEnd;
  
  NSInteger _nBodyId;
  Byte _nWgtUnit;
  
  //move smoothly
  //UIScrollView* _svGraphView;
  CGFloat _yHgtCtrl;
  CGFloat _xScreenSize;
  //CGFloat _xLastMovePos;
  
  BOOL _bIpad;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view.
  //self.view.backgroundColor = [UIColor colorWithWhite:0.125 alpha:0.5];
    
  CGRect frame = [[UIScreen mainScreen] bounds];
  CGFloat W = frame.size.width;
  CGFloat H = frame.size.height;
  _xScreenSize = W;
  _bIpad = H > 1000;
  
  //AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //UIImage* imgback = [pApp getImageScale:(_bIpad?@"ic-mainbkgd2@1024.png":@"ic-mainbkgd2.png") scale:(_bIpad?1.0:0.32)];
//  [self.view setBackgroundColor:[UIColor colorWithPatternImage:imgback]];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.view.frame];
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    imgView.image = [UIImage imageNamed:@"ic-mainbkgd2"];
    [self.view insertSubview:imgView atIndex:0];
    
  CGFloat yPos = (H <= 480)? 60: 65;
  [self initViewCtrls: yPos scrWdt: W scrHgt:H];
  
  //UIImage* iProf = [pApp getImageScale:@"ic-list.png" scale: 0.4];
  //UIBarButtonItem *profButton = [[UIBarButtonItem alloc] initWithImage:iProf style:UIBarButtonItemStylePlain target:self action:@selector(mainAction:)];
  //self.navigationItem.leftBarButtonItem = leftButton;
  //self.navigationItem.rightBarButtonItem = profButton;

    
  _values = [[NSMutableArray alloc]init];
  
  _ptViewWgt = _gViewWgt.center;
  _ptViewFat = _gViewFat.center;
  
  _bShowWgt = YES;
  _bSyncEnd = NO;
  [self chgDateRng:_scDateRng];
  
  //sync
  _nBodyId = 0;
  _progView = nil;
  _actView = nil;
  _nSyncPos = 0;
  
  NSURLSessionConfiguration* cnfgSession = [NSURLSessionConfiguration defaultSessionConfiguration];// [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier: @"HrateSync"];
  cnfgSession.timeoutIntervalForRequest = 10.0; 
  _netSession = [NSURLSession sessionWithConfiguration:cnfgSession delegate: self delegateQueue: nil];

//  UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
//  [btnBack setImage:[UIImage imageNamed:@"btn-left-w.png"] forState:UIControlStateNormal];//@"btn_back.png"
//  [btnBack addTarget:self action:@selector(onRtnRegWait:) forControlEvents:UIControlEventTouchUpInside];
//  
//  //UIBarButtonItem* btniBack = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRedo target:self action:@selector(onRtnRegWait:)];
//  UIBarButtonItem* btniBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
//  self.navigationItem.leftBarButtonItem = btniBack;
}

- (void) initViewCtrls:(CGFloat) yPos scrWdt:(CGFloat)W scrHgt:(CGFloat)H
{
  BOOL bIpad = H > 1000;
  BOOL bIp6p = H >= 667;
  BOOL bWider = NO, bIp6 = NO, bIp5 = NO, bIp4s = NO;
  if(!bIp6p) {
    bIp6 = H > 568;
    bWider = W > 320;
    bIp5 = H  == 568;
    bIp4s = H <= 480;
  }
    //BOOL bPlus = !bIpad && H >= 736;
    int disH = H / 25;
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
  _lblMsg = [[UILabel alloc] initWithFrame:CGRectMake(20, yPos, W-40, 25 + disH)];
  _lblMsg.textColor = DefaultColor;
  _lblMsg.font = [UIFont fontWithName:@"Calibri" size:16.0];
  _lblMsg.backgroundColor = [UIColor clearColor];
  _lblMsg.textAlignment = NSTextAlignmentCenter;
  _lblMsg.text = [NSString stringWithFormat:NSLocalizedString(@"Weight for %@ %@", nil), pApp.m_bodyInfo.sFirst, pApp.m_bodyInfo.sLast];
    [self.view addSubview:_lblMsg];
    
    //h an v lines
  CGRect rt;
  UIImage* iConh = [[UIImage imageNamed:@"ic-horline.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  CGFloat fHgt = iConh.size.height * 2 / 3; //W * iConh.size.height / iConh.size.width;
    rt.origin.x = 0;
    rt.origin.y = yPos + 25 + disH;//(H / 2.0) + (bIpad? 115: (bIp4s?40:(bWider?85:65)));
  rt.size.height = fHgt;
    rt.size.width = W;
    rt.size.height = LineH;
    _ivhLine1  = [[UIImageView alloc] initWithFrame:rt];
//    [_ivhLine1 setImage:iConh];
    _ivhLine1.alpha = LineA;
    _ivhLine1.backgroundColor = LineColor;
    [self.view addSubview:_ivhLine1];
    
    //UIImage* iConv = [[UIImage imageNamed:@"ic-verline.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  //®fHgt = iConv.size.width;
    rt.origin.x = W / 2.0 - fHgt / 2.0;
    rt.origin.y = rt.origin.y + fHgt/10 + 10;
    rt.size.height = H / 8 + (bIpad?0:20) - 20;
    rt.size.width = fHgt;//iCon.size.width;
    
    _ivvLinet  = [[UIView alloc] init];
    _ivvLinet.alpha = LineA;
    _ivvLinet.backgroundColor = LineColor;
//    [_ivvLinet setImage:iConv];
    [self.view addSubview:_ivvLinet];
    
    rt.origin.x = 0;
  rt.origin.y += rt.size.height - (bIpad?10: (bWider?15:(bIp4s?-2:5))) + (bIp4s?5:20);
    rt.size.height = fHgt;
    rt.size.width = W;
    rt.size.height = LineH;
    _ivhLine2 = [[UIView alloc] initWithFrame:rt];
    _ivhLine2.alpha = LineA;
    _ivhLine2.backgroundColor = LineColor;
    _ivvLinet.frame = CGRectMake(W / 2, CGRectGetMaxY(_ivhLine1.frame), LineH,CGRectGetMaxY(_ivhLine2.frame) - CGRectGetMaxY(_ivhLine1.frame));
//    [_ivhLine2 setImage:iConh];
    [self.view addSubview:_ivhLine2];
    
    //wgt label tips
    CGFloat yyPos = yPos + 30;
    _lblWgtTip = [[UILabel alloc] initWithFrame:CGRectMake(20, yyPos + 55 + disH + H / 90, W/2-40, 25)];
    _lblWgtTip.textColor = CustomColor;
    _lblWgtTip.font = [UIFont fontWithName:@"Calibri" size:15.0];
    _lblWgtTip.backgroundColor = [UIColor clearColor];
    _lblWgtTip.textAlignment = NSTextAlignmentCenter;
    _lblWgtTip.text = NSLocalizedString(@"Last Weight", nil);
    [self.view addSubview:_lblWgtTip];
    
    _lblWgtLast = [[UILabel alloc] initWithFrame:CGRectMake(2, yyPos+(bIpad?30:20) - 25 + disH, W/3+18, 60)];
    _lblWgtLast.textColor = DefaultColor;
    _lblWgtLast.font = Bold(H / 17);
    _lblWgtLast.backgroundColor = [UIColor clearColor];
    _lblWgtLast.textAlignment = NSTextAlignmentCenter;
    _lblWgtLast.text = @"---.-kg";
    [self.view addSubview:_lblWgtLast];
    _lblWgtLast.centerX = _lblWgtTip.centerX;
    
  _lblWgtUnit = [[UILabel alloc] initWithFrame:CGRectMake(W/3+22, yyPos+(bIpad?55:50), bIpad?60:40, bIpad?40:25)];
    _lblWgtUnit.textColor = DefaultColor;
    _lblWgtUnit.font = [UIFont boldSystemFontOfSize:bIpad?35:25];
    _lblWgtUnit.backgroundColor = [UIColor clearColor];
    _lblWgtUnit.textAlignment = NSTextAlignmentLeft;
    _lblWgtUnit.text = @"kg";
    _lblWgtUnit.centerY = _lblWgtLast.centerY;
//    [self.view addSubview:_lblWgtUnit];
    
    _lblGoalTip = [[UILabel alloc] initWithFrame:CGRectMake(W/2+20, yyPos + disH + H / 90, W/2-40, 25)];
    _lblGoalTip.textColor = CustomColor;
    _lblGoalTip.font = [UIFont fontWithName:@"Calibri" size:15.0];
    _lblGoalTip.backgroundColor = [UIColor clearColor];
    _lblGoalTip.textAlignment = NSTextAlignmentCenter;
    _lblGoalTip.text = NSLocalizedString(@"Goal Weight", nil);
    _lblGoalTip.centerY = _lblWgtTip.centerY;
    [self.view addSubview:_lblGoalTip];
    
    _lblGoalWgt =[[UILabel alloc] initWithFrame:CGRectMake(W/2+10, yyPos+(bIpad?30:20) + disH, W/3+18, 60)];
    _lblGoalWgt.textColor = DefaultColor;
    _lblGoalWgt.font = Bold(H / 17);
    _lblGoalWgt.backgroundColor = [UIColor clearColor];
    _lblGoalWgt.textAlignment = NSTextAlignmentCenter;
    _lblGoalWgt.text = @"---.-kg";
    _lblGoalWgt.centerY = _lblWgtLast.centerY;
    [self.view addSubview:_lblGoalWgt];
    _lblGoalWgt.centerX = _lblGoalTip.centerX;
  //Byte nWgtUn = pApp.m_bodyInfo.nWgtUn;
  _lblGoalUnit =[[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_lblGoalWgt.frame) - 10, yyPos+(bIpad?55:bIp6p?50:bIp6?48:45), bIpad?60:40, bIpad?40:25)];
  _lblGoalUnit.textColor = DefaultColor;
  _lblGoalUnit.font = [UIFont boldSystemFontOfSize:bIpad?32:22];
  _lblGoalUnit.backgroundColor = [UIColor clearColor];
  _lblGoalUnit.textAlignment = NSTextAlignmentLeft;
  _lblGoalUnit.text = @"kg";
    _lblGoalUnit.centerY = _lblWgtLast.centerY;
//  [self.view addSubview:_lblGoalUnit];
    
    //graph
  yyPos = rt.origin.y+rt.size.height+(bIpad?10:(bWider?5:1));
  CGFloat fGhgt = H * 2 / 3 - rt.origin.y;
  if(bIp4s)
    fGhgt = fGhgt *  0.985;
  _yHgtCtrl = fGhgt;


  
  //last wgt unit
  short nLastWgtUnit = 2;
  NSMutableArray* pData = [NSMutableArray arrayWithArray:[pApp loadWgtData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:NO last:YES]];
  if(pData != nil && pData.count > 0) {
    N_WgtData* pWgt = [pData objectAtIndex:0];
    nLastWgtUnit = pWgt.mWgtUnit.shortValue;
    //_nWgtUnit = nLastWgtUnit;
  }
  
  //_svGraphView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, yyPos, W*2,fGhgt)];
  
  CGRect chartFrame  = CGRectMake(5, yyPos + 15 + H / 9 * 0.4, W-10, fGhgt);
  _gViewWgt = [[UIGraphView alloc] initWithFrame: chartFrame];
  //_gViewWgt.center = CGPointMake(chartFrame.size.width/2.0, chartFrame.size.height/2);
  _gViewWgt.delegate = self;
  _gViewWgt.dataSource = self;
  _gViewWgt.barShadowOffset = CGSizeMake(2.0, 1.0);
  _gViewWgt.animationDuration = 0.0;
  _gViewWgt.barShadowColor	 = [UIColor grayColor];
  _gViewWgt.barShadowAlpha	 = 0.5;
  _gViewWgt.barShadowRadius = 1.0;
  //_gViewWgt.barWidth = (W-10) / 9;//chartFrame.size.width / 10.0;
  _gViewWgt.xLabelType	 = GraphViewXLabelTypeHorizontal;
  //_gViewWgt.incrementValue = 50;
  _gViewWgt.barTextType = GraphViewBarTextTypeTop;
  _gViewWgt.barTextColor = [UIColor whiteColor];
  _gViewWgt.gridColor = [UIColor grayColor];
    _gViewWgt.lblMeasUnit.textColor = DefaultColor;
  //_gViewWgt.backgroundColor = [UIColor grayColor];
  //_gViewWgt.frame = chartFrame;
  
  _gViewWgt.nSetUnit = nLastWgtUnit; //pApp.m_bodyInfo.nWgtUn;
  _nWgtUnit = nLastWgtUnit; //pApp.m_bodyInfo.nWgtUn;
  
  [self.view addSubview:_gViewWgt];
  _gViewWgt.hidden = NO;
  //[_svGraphView addSubview:_gViewWgt];
  
  //chartFrame.origin.x += W;
  _gViewFat = [[UIGraphView alloc] initWithFrame: chartFrame];
  _gViewFat.center = CGPointMake(chartFrame.size.width/2.0, chartFrame.size.height/2);
  _gViewFat.delegate = self;
  _gViewFat.dataSource = self;
  _gViewFat.barShadowOffset = CGSizeMake(2.0, 1.0);
  _gViewFat.animationDuration = 0.0;
  _gViewFat.barShadowColor	 = [UIColor grayColor];
  _gViewFat.barShadowAlpha	 = 0.5;
  _gViewFat.barShadowRadius = 1.0;
  _gViewFat.xLabelType	 = GraphViewXLabelTypeHorizontal;
  _gViewFat.barTextType = GraphViewBarTextTypeTop;
  _gViewFat.barTextColor = [UIColor whiteColor];
  _gViewFat.gridColor = [UIColor grayColor];
  _gViewFat.frame = chartFrame;
  _gViewFat.nSetUnit = 6;
    _gViewFat.lblMeasUnit.textColor = DefaultColor;
  [self.view addSubview:_gViewFat];
  //[_svGraphView addSubview:_gViewFat];
  _gViewFat.hidden = YES;
  //[self.view addSubview:_svGraphView];
  
    
    CGFloat xPos = bIpad? 100: bWider? 80:65;
  yyPos = _gViewWgt.frame.origin.y + _gViewWgt.frame.size.height - (bIpad?12:bIp6?-10: 0);
    
    _lblDatRngTip = [[UILabel alloc] initWithFrame:CGRectMake(5, yyPos - 10, xPos - 5, 30)];
    _lblDatRngTip.textColor = DefaultColor;
    _lblDatRngTip.font = Bold(15);
    _lblDatRngTip.backgroundColor = [UIColor clearColor];
    _lblDatRngTip.textAlignment = NSTextAlignmentCenter;
//    _lblDatRngTip.text = @"Timeline";
    [self.view addSubview:_lblDatRngTip];
    
    _scDateRng = [[UISegmentedControl alloc]initWithFrame:CGRectMake(xPos, yyPos + H / 9 * 0.4, W-xPos-10, 30)];
    //UIColor* bgColor = [UIColor colorWithRed:0.98 green:0.45 blue:0.05 alpha:0.25];
    //_scDateRng. = bgColor;
    //_scDateRng.tintColor = [UIColor lightGrayColor];
    _scDateRng.tintColor = [UIColor clearColor];
    _scDateRng.centerY = _lblDatRngTip.centerY;
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16], NSForegroundColorAttributeName: DefaultColor};
    [_scDateRng setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16], NSForegroundColorAttributeName: [UIColor blackColor]};
    [_scDateRng setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];

  [_scDateRng insertSegmentWithTitle:@"All" atIndex:0 animated:NO];
  [_scDateRng insertSegmentWithTitle:@"1 D" atIndex:1 animated:NO];
  [_scDateRng insertSegmentWithTitle:@"1 W" atIndex:2 animated:NO];
  [_scDateRng insertSegmentWithTitle:@"1 M" atIndex:3 animated:NO];
  //[_scDateRng insertSegmentWithTitle:@"3 M" atIndex:3 animated:NO];
  [_scDateRng insertSegmentWithTitle:@"6 M" atIndex:4 animated:NO];
  [_scDateRng insertSegmentWithTitle:@"1 Y" atIndex:5 animated:NO];
  _scDateRng.selectedSegmentIndex = 3;
  [_scDateRng addTarget: self action:@selector(chgDateRng:) forControlEvents:UIControlEventValueChanged];
  [self.view addSubview:_scDateRng];
  
  //sync
  xPos = W - (bIpad?82:(bIp4s?58:66));
  yyPos =  H * 2 / 3 + (bIpad?50:bIp6p?50:(bIp4s?30:bIp6?50:bIp5?30:30));
  UIImage* iBtn = [[UIImage imageNamed:@"btn-sync-bl.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  _btnSyncData = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnSyncData.frame = CGRectMake(xPos, yyPos + H / 9 * 0.4, bIpad?72:(bIp4s?48:56), bIpad?72:(bIp4s?48:56));
  [_btnSyncData setBackgroundImage:iBtn forState:UIControlStateNormal];
  [_btnSyncData addTarget:self action:@selector(tapStartSync:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnSyncData];
  
  yyPos +=  (bIpad?90:(bIp4s?0:bIp6?0:bIp5?60:60));
    
    //bottom linesF    yyPos = H * 5 / 6;
    rt.origin.y = yyPos + H / 9 * 0.4;
//    rt.size.height = fHgt;
    rt.size.height = LineH;
    rt.size.width = W;
    _ivhLineb = [[UIView alloc] initWithFrame:rt];
//    [_ivhLineb setImage:iConh];
    _ivhLineb.backgroundColor = LineColor;
    _ivhLineb.alpha = LineA;
    [self.view addSubview:_ivhLineb];
    
    xPos = W / 4;
    rt.origin.x = xPos;
    rt.origin.y = yyPos + H/100;
    rt.size.height = H / 8 + (bIpad?40:35);
    rt.size.width = fHgt;//iCon.size.width;
  
  rt.origin.y += 10;
  rt.size.height -= 20;
  rt.size.width = fHgt / 2;
    _ivvLineb1  = [[UIView alloc] initWithFrame:CGRectMake(W / 4, CGRectGetMaxY(_ivhLineb.frame), LineH, 500)];
//    [_ivvLineb1 setImage:iConv];
    _ivvLineb1.backgroundColor = LineColor;
    _ivvLineb1.alpha = LineA;
    [self.view addSubview:_ivvLineb1];

    rt.origin.x += W / 4;
    _ivvLineb2  = [[UIView alloc] initWithFrame:CGRectMake(W / 2, CGRectGetMaxY(_ivhLineb.frame), LineH, 500)];
//    [_ivvLineb2 setImage:iConv];
    _ivvLineb2.backgroundColor = LineColor;
    _ivvLineb2.alpha = LineA;
    [self.view addSubview:_ivvLineb2];

    rt.origin.x += W / 4;
//    [_ivvLineb3 setImage:iConv];
    _ivvLineb3  = [[UIView alloc] initWithFrame:CGRectMake(W / 4 * 3, CGRectGetMaxY(_ivhLineb.frame), LineH, 500)];
    //    [_ivvLineb2 setImage:iConv];
    _ivvLineb3.backgroundColor = LineColor;
    _ivvLineb3.alpha = LineA;
    [self.view addSubview:_ivvLineb3];
    
    xPos = 5;
    yyPos += bIpad? 5: bWider?5: bIp4s?-2:5;
    _lblWgtLstTip[0] = [[UILabel alloc] initWithFrame:CGRectMake(xPos, H / 18 * 16.6, W/4-10, 50)];
    _lblWgtLstTip[0].textColor = [UIColor blackColor];
    _lblWgtLstTip[0].font = Semibold(13);
    _lblWgtLstTip[0].backgroundColor = [UIColor clearColor];
    _lblWgtLstTip[0].textAlignment = NSTextAlignmentCenter;
    _lblWgtLstTip[0].lineBreakMode = NSLineBreakByWordWrapping;
    _lblWgtLstTip[0].numberOfLines = 0;
    _lblWgtLstTip[0].text = NSLocalizedString(@"Weight loss\n to date", nil);
    [self.view addSubview:_lblWgtLstTip[0]];
    
    xPos += W / 4;
    _lblWgtLstTip[1] = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yyPos ,W/4-10, 50)];
    _lblWgtLstTip[1].textColor = [UIColor blackColor];
    _lblWgtLstTip[1].font = Semibold(13);
    _lblWgtLstTip[1].backgroundColor = [UIColor clearColor];
    _lblWgtLstTip[1].textAlignment = NSTextAlignmentCenter;
    _lblWgtLstTip[1].lineBreakMode = NSLineBreakByWordWrapping;
    _lblWgtLstTip[1].numberOfLines = 0;
    _lblWgtLstTip[1].text = NSLocalizedString(@"% Weight loss", nil);
    _lblWgtLstTip[1].centerY = _lblWgtLstTip[0].centerY;
    [self.view addSubview:_lblWgtLstTip[1]];
    
    xPos += W / 4;
    _lblWgtLstTip[2] = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yyPos , W/4-10, 50)];
    _lblWgtLstTip[2].textColor = [UIColor blackColor];
    _lblWgtLstTip[2].font = Semibold(13);
    _lblWgtLstTip[2].backgroundColor = [UIColor clearColor];
    _lblWgtLstTip[2].textAlignment = NSTextAlignmentCenter;
    _lblWgtLstTip[2].lineBreakMode = NSLineBreakByWordWrapping;
    _lblWgtLstTip[2].numberOfLines = 0;
    _lblWgtLstTip[2].text = NSLocalizedString(@"% to Goal", nil);
    _lblWgtLstTip[2].centerY = _lblWgtLstTip[0].centerY;
    [self.view addSubview:_lblWgtLstTip[2]];
    
    xPos += W / 4;
    _lblWgtLstTip[3] = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yyPos , W/4-10, 50)];
    _lblWgtLstTip[3].textColor = [UIColor blackColor];
    _lblWgtLstTip[3].font = Semibold(13);
    _lblWgtLstTip[3].backgroundColor = [UIColor clearColor];
    _lblWgtLstTip[3].textAlignment = NSTextAlignmentCenter;
    _lblWgtLstTip[3].lineBreakMode = NSLineBreakByWordWrapping;
    _lblWgtLstTip[3].numberOfLines = 0;
    _lblWgtLstTip[3].text = NSLocalizedString(@"Current Fat", nil);
    _lblWgtLstTip[3].centerY = _lblWgtLstTip[0].centerY;
    [self.view addSubview:_lblWgtLstTip[3]];
    
    //summary date val
    xPos = 2;
    yyPos += bIpad? 75: bWider?45 : bIp4s?32:36;
    CGFloat fValCtrlWid =  W/4-(bIpad?60:30);
    _lblWgtLstVal[0] = [[UILabel alloc] initWithFrame:CGRectMake(xPos, H / 9 * 7.9, fValCtrlWid, 50)];
    _lblWgtLstVal[0].textColor = DefaultColor;
    _lblWgtLstVal[0].font = Bold(H / 34);
    _lblWgtLstVal[0].backgroundColor = [UIColor clearColor];
    _lblWgtLstVal[0].textAlignment = NSTextAlignmentCenter;
    _lblWgtLstVal[0].text = @"--.- kg";
    _lblWgtLstVal[0].centerX = _lblWgtLstTip[0].centerX;
    [self.view addSubview:_lblWgtLstVal[0]];

    _lblWgtLstUn[0] = [[UILabel alloc] initWithFrame:CGRectMake(xPos+fValCtrlWid+2, yyPos+5, 30, 50)];
    _lblWgtLstUn[0].textColor = DefaultColor;
    _lblWgtLstUn[0].font = Bold(H / 34);
    _lblWgtLstUn[0].backgroundColor = [UIColor clearColor];
    _lblWgtLstUn[0].textAlignment = NSTextAlignmentLeft;
    _lblWgtLstUn[0].text = @"kg";
    _lblWgtLstUn[0].centerY = _lblWgtLstVal[0].centerY;
//    [self.view addSubview:_lblWgtLstUn[0]];
    
    xPos += W / 4;
    _lblWgtLstVal[1] = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yyPos , fValCtrlWid, 50)];
    _lblWgtLstVal[1].textColor = DefaultColor;
    _lblWgtLstVal[1].font = Bold(H / 34);
    _lblWgtLstVal[1].backgroundColor = [UIColor clearColor];
    _lblWgtLstVal[1].textAlignment = NSTextAlignmentCenter;
    _lblWgtLstVal[1].text = @"--.- %";
    _lblWgtLstVal[1].centerY = _lblWgtLstVal[0].centerY;
    _lblWgtLstVal[1].centerX = _lblWgtLstTip[1].centerX;
    [self.view addSubview:_lblWgtLstVal[1]];
    
    _lblWgtLstUn[1] = [[UILabel alloc] initWithFrame:CGRectMake(xPos+fValCtrlWid+2, yyPos+5, 30, 50)];
    _lblWgtLstUn[1].textColor = DefaultColor;
    _lblWgtLstUn[1].font = Bold(H / 34);
    _lblWgtLstUn[1].backgroundColor = [UIColor clearColor];
    _lblWgtLstUn[1].textAlignment = NSTextAlignmentLeft;
    _lblWgtLstUn[1].text = @"%";
    _lblWgtLstUn[1].centerY = _lblWgtLstVal[0].centerY;
//    [self.view addSubview:_lblWgtLstUn[1]];
    
    xPos += W / 4;
    _lblWgtLstVal[2] = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yyPos ,fValCtrlWid, 50)];
    _lblWgtLstVal[2].textColor = DefaultColor;
    _lblWgtLstVal[2].font = Bold(H / 34);
    _lblWgtLstVal[2].backgroundColor = [UIColor clearColor];
    _lblWgtLstVal[2].textAlignment = NSTextAlignmentCenter;
    _lblWgtLstVal[2].text = @"--.- %";
    _lblWgtLstVal[2].centerY = _lblWgtLstVal[0].centerY;
    _lblWgtLstVal[2].centerX = _lblWgtLstTip[2].centerX;
    [self.view addSubview:_lblWgtLstVal[2]];
    
    _lblWgtLstUn[2] = [[UILabel alloc] initWithFrame:CGRectMake(xPos+fValCtrlWid+2, yyPos+5, 30, 50)];
    _lblWgtLstUn[2].textColor = DefaultColor;
    _lblWgtLstUn[2].font = Bold(H / 34);
    _lblWgtLstUn[2].backgroundColor = [UIColor clearColor];
    _lblWgtLstUn[2].textAlignment = NSTextAlignmentLeft;
    _lblWgtLstUn[2].text = @"%";
    _lblWgtLstUn[2].centerY = _lblWgtLstVal[0].centerY;
//    [self.view addSubview:_lblWgtLstUn[2]];
    
    xPos += W / 4;
    _lblWgtLstVal[3] = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yyPos , fValCtrlWid, 50)];
    _lblWgtLstVal[3].textColor = DefaultColor;
    _lblWgtLstVal[3].font = Bold(H / 34);
    _lblWgtLstVal[3].backgroundColor = [UIColor clearColor];
    _lblWgtLstVal[3].textAlignment = NSTextAlignmentCenter;
    _lblWgtLstVal[3].text = @"--.- %";
    _lblWgtLstVal[3].centerY = _lblWgtLstVal[0].centerY;
    _lblWgtLstVal[3].centerX = _lblWgtLstTip[3].centerX;
    [self.view addSubview:_lblWgtLstVal[3]];
    
    _lblWgtLstUn[3] = [[UILabel alloc] initWithFrame:CGRectMake(xPos+fValCtrlWid+2, yyPos+5, 30, 50)];
    _lblWgtLstUn[3].textColor = DefaultColor;
    _lblWgtLstUn[3].font = Bold(H / 34);
    _lblWgtLstUn[3].backgroundColor = [UIColor clearColor];
    _lblWgtLstUn[3].textAlignment = NSTextAlignmentLeft;
    _lblWgtLstUn[3].text = @"%";
    _lblWgtLstUn[3].centerY = _lblWgtLstVal[0].centerY;
//    [self.view addSubview:_lblWgtLstUn[3]];
}

//- (void) onRtnRegWait:(id)sender
//{
//  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//  [pApp enterMainPage];
//}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
  _lblMsg.text = NSLocalizedString(@"No enough memory!", nil);
  AudioServicesPlaySystemSound(1112);
}

- (void) viewWillAppear:(BOOL)animated
{
  //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //_gViewWgt.nSetUnit = pApp.m_bodyInfo.nWgtUn;
  //_nWgtUnit = _gViewWgt.nSetUnit;
  
  [self setLastGoalWgt];
  //[_gViewWgt reloadData];
}

- (void) viewWillDisappear:(BOOL)animated
{
   [_netSession invalidateAndCancel];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void) setLastGoalWgt
{
    float fLastWgt = 0;
    short nWgtUnit = 2;
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    NSMutableArray* pData = [NSMutableArray arrayWithArray:[pApp loadWgtData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:NO last:YES]];
    if(pData != nil && pData.count > 0) {
      N_WgtData* pWgt = [pData objectAtIndex:0];
      fLastWgt = pWgt.mWgtData.floatValue;
      nWgtUnit = pWgt.mWgtUnit.shortValue;
      _nWgtUnit = nWgtUnit;
    }
    _lblWgtLast.text = (fLastWgt >0)?[NSString stringWithFormat:@"%.1f kg", fLastWgt]:@"---.-";
    //_lblWgtLast.text = @"234.5";
    _lblWgtUnit.text = (nWgtUnit==2)?@"kg": @"kg";
  
  short nGoalWgtUn = (short)pApp.m_bodyInfo.nWgtUn;
  _lblGoalWgt.text = [NSString stringWithFormat:@"%.1f kg", pApp.m_bodyInfo.fGoalWgt];
  _lblGoalUnit.text = (nGoalWgtUn==2)?@"kg": @"kg";
  _lblWgtLstUn[0].text = _lblGoalUnit.text;
  
  if(nWgtUnit != nGoalWgtUn) {
    if(nWgtUnit == 1)
      fLastWgt /= _LbtoKg;
    else
      fLastWgt *= _LbtoKg;
  }
    
  float fInitWgt = pApp.m_bodyInfo.fBodyWgt;
  float fGoalWgt = pApp.m_bodyInfo.fGoalWgt;
  float fWgtLoss = (fLastWgt>0)?fInitWgt-fLastWgt: 0;
  
  fInitWgt = roundf (fInitWgt * 10) / 10.0;
  fLastWgt =  roundf (fLastWgt * 10) / 10.0;
  fWgtLoss =  roundf (fWgtLoss * 10) / 10.0;
  float fGoalLen = roundf((fInitWgt - fGoalWgt)* 10) /10.0;
  float fLossRate = (fLastWgt>0)? (fInitWgt-fLastWgt) * 100 / fInitWgt:0;
  
  /*if(nGoalWgtUn != nWgtUnit) {
    if(nGoalWgtUn == 2)
      fWgtLoss *= _KgtoLb;
    else
      fWgtLoss /= _KgtoLb;
  }*/
  
  float fToGoal = 0.0;
  if(fGoalLen != 0)
    fToGoal = fWgtLoss * 100.0 / fGoalLen;
    
   _lblWgtLstVal[0].text = (fLastWgt != 0)?[NSString stringWithFormat:@"%.1f %@", fWgtLoss,@"kg"]: @"--.- kg";
   _lblWgtLstVal[1].text = (fLastWgt != 0)?[NSString stringWithFormat:@"%.1f %@", fLossRate,@"%"]: @"--.- %";
   _lblWgtLstVal[2].text = (fToGoal != 0)?[NSString stringWithFormat:@"%.1f %@", fToGoal,@"%"]: @"--.- %";
    
    //fat
    float fLfat = 0;
    pData = [NSMutableArray arrayWithArray:[pApp loadFatData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:NO last:YES]];
    if(pData != nil && pData.count > 0) {
        N_FatData* pFat = (N_FatData*)[pData objectAtIndex:0];
        if (pFat != nil && pFat.fatVal != nil)
            fLfat = pFat.fatVal.floatValue;
    }
    _lblWgtLstVal[3].text =  (fLfat >0)?[NSString stringWithFormat:@"%.1f %@", fLfat,@"%"]:@"--.- %";
    _gViewWgt.nSetUnit = _nWgtUnit;
}

- (NSTimeInterval) getTimeOffset:(NSInteger)nRngIdx
{
    NSTimeInterval dtInterval = _OneDaySeconds;
    //dtInterval = dtInterval * 6.0  +  dtInterval * nRngIdx * 7;
    if(nRngIdx == 1)
        dtInterval *= 0.75;
    else if(nRngIdx == 2)
        dtInterval *= 6;
    else if(nRngIdx == 3)
        dtInterval *= 30;
    else if(nRngIdx == 4)
        dtInterval *= 183;
    else if(nRngIdx == 5)
        dtInterval *= 365;
    
    dtInterval = -dtInterval;
    
    return dtInterval;
}

-(void) chgDateRng:(id)sender
{
    [_values removeAllObjects];
    if(sender != nil)
        _nDtRngIdx = _scDateRng.selectedSegmentIndex;
    else
        _nDtRngIdx = 0;
    
    //date rng
    [_pWgtData removeAllObjects];
    [_pFatData removeAllObjects];
    
    NSTimeInterval dtInterval = [self getTimeOffset:_nDtRngIdx];
    _dtFr = [[NSDate date] dateByAddingTimeInterval:dtInterval];
    _dtTo = [[NSDate date] dateByAddingTimeInterval:_OneDaySeconds];
    
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if(_nDtRngIdx == 0) {
        _pWgtData = [NSMutableArray arrayWithArray:[pApp loadWgtData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:YES last:NO]];
        _pFatData = [NSMutableArray arrayWithArray:[pApp loadFatData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:YES last:NO]];
    }
    else {
        _pWgtData = [NSMutableArray arrayWithArray:[pApp loadWgtData:pApp.m_bodyInfo.m_nBodyId from:_dtFr to:_dtTo sort:YES last:NO]];
        _pFatData = [NSMutableArray arrayWithArray:[pApp loadFatData:pApp.m_bodyInfo.m_nBodyId from:_dtFr to:_dtTo sort:YES last:NO]];
    }
    [self showWgtFatData:_pWgtData fat:_pFatData];

    
    //_lblMsg.text = @"Date rng chged";
    AudioServicesPlaySystemSound(1109);
}

-(void)mainAction:(id)sender  
{  
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp enterPageWithRes:@"bodyProfViewCtrl"];
}

- (void) showWgtFatData:(NSMutableArray*) pWgtData fat:(NSMutableArray*) pFatData
{
  NSUInteger nWgt = pWgtData.count;
  NSUInteger nFat = pFatData.count;
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(nWgt == 0 && nFat == 0) {
    NSString* sTitle = [NSString stringWithFormat:NSLocalizedString(@"No any data for %@ %@", nil),  pApp.m_bodyInfo.sFirst, pApp.m_bodyInfo.sLast/*pApp.m_bodyInfo.sEmail*/];
    _lblMsg.text = sTitle;
      //return;
  }
  else if(!_bSyncEnd) {
    NSString* sMsg = _bShowWgt?NSLocalizedString(@"Body Weight", nil) : NSLocalizedString(@"Body Fat", nil);
    NSString* sTitle =  [NSString stringWithFormat:@"%@ for %@ %@", sMsg, pApp.m_bodyInfo.sFirst, pApp.m_bodyInfo.sLast/*pApp.m_bodyInfo.sEmail*/];
   _lblMsg.text = sTitle;
  }
  
  
  [self setWgtInitData];
  [_gViewWgt reloadDataWithColor:DefaultColor];

  [self setFatInitData];
  [_gViewFat reloadDataWithColor:DefaultColor];
   
  _bSyncEnd = NO;
}

- (void) formNewWgtData:(N_WgtData*) lastData sum:(double)dSum count:(int)nCount
{
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
    NSDateFormatter* _dtFmt = pApp.dtFmt;
    [_dtFmt setDateFormat:@"MM/dd"];
    
    double dAvgWgt = (nCount != 0)? dSum/nCount: [lastData.mWgtData doubleValue];
    WiFiScaleData* newObj = [[WiFiScaleData alloc] init];
    
    NSDate* sOsTime = lastData.iOsDateTime;
    NSDate* sScaTime = lastData.scaDateTime;
    [newObj formWgtData:[_dtFmt stringFromDate:sOsTime] wgtVal:dAvgWgt unit:(int)[lastData.mWgtUnit integerValue]
                                           dtScale:[_dtFmt stringFromDate:sScaTime]];
    double dInterval = [lastData.iOsDateTime timeIntervalSinceDate:_lastDatePos] / _DaySeconds;
    newObj.dDatePos = (float)dInterval;
    [_values addObject:newObj];
    
    [pApp.dtFmt setDateFormat:sInitDtFmt];
}

//datasource and delegate
- (UIColor *)barChartColor
{
    return DefaultColor;
}

- (NSUInteger)numberOfBarsInBarChart:(UIGraphView *)barChart
{
  BOOL bShowWgt = barChart.nSetUnit < 6;
  if(bShowWgt) {
    return _pWgtData.count;
  }
  else {
    return _pFatData.count;
  }
}

- (CGFloat)barChart:(UIGraphView *)barChart valueForBarAtIndex:(NSUInteger)index
{
  BOOL bShowWgt = barChart.nSetUnit < 6;
  
  if(bShowWgt) {
    if(_pWgtData == nil || _pWgtData.count < index+1)
      return 0.0;
      
    N_WgtData* nWgt = [_pWgtData objectAtIndex:index];
    CGFloat fWgt = nWgt.mWgtData.floatValue;
    if(nWgt.mWgtUnit.shortValue != _nWgtUnit && _nWgtUnit != 0) {
      if(_nWgtUnit == 2)
        fWgt *= _KgtoLb;
      else
        fWgt *= _LbtoKg;
    }
    return fWgt;
  }
  else {
    if(_pFatData == nil || _pFatData.count < index+1)
      return 0.0;
        
    N_FatData* nFat = [_pFatData objectAtIndex:index];
    CGFloat fFat = nFat.fatVal.floatValue;
    if(fFat > 99)
      fFat = 99;
    return fFat;
  }
}

- (CGFloat)barChart:(UIGraphView *)barChart xposForBarAtIndex:(NSUInteger)index
{
  BOOL bShowWgt =  barChart.nSetUnit < 6;
  
  if(bShowWgt) {
     if(index >= _pWgtData.count)
       return 0.0;
    N_WgtData* nWgt = [_pWgtData objectAtIndex:index];
    if(nWgt != nil) {
      //CGFloat dInterval = [nWgt.iOsDateTime timeIntervalSinceDate:_lastDatePos] / _DaySeconds;
      CGFloat dInterval = index * 10;
      return dInterval;
    }
    else {
      return 0.0f;
    }
  }
  else {
    if(index >= _pFatData.count)
      return 0.0;
    N_FatData* nFat = [_pFatData objectAtIndex:index];
    if(nFat != nil) {
      //CGFloat dInterval = [nFat.measDate timeIntervalSinceDate:_lastDatePos] / _DaySeconds;
      CGFloat dInterval = index * 10;
      return dInterval;
    }
    else {
      return 0.0f;
    }
  }
}

- (NSString *)barChart:(UIGraphView *)barChart xLabelForBarAtIndex:(NSUInteger)index
{
  BOOL bShowWgt =  barChart.nSetUnit < 6;
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(bShowWgt) {
    NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
    NSDateFormatter* dtFmt = pApp.dtFmt;
    [dtFmt setDateFormat:@"MM/dd"];
      
    N_WgtData *nWgt = [_pWgtData objectAtIndex:index];
    NSString* sTxt = [dtFmt stringFromDate:nWgt.iOsDateTime];
    
    if(index == 0) {
      [dtFmt setDateFormat:@"MM/dd/yyyy"];
      //[dtFmt setDateFormat:@"MM:dd"];
      sTxt = [dtFmt stringFromDate:nWgt.iOsDateTime];
    }
    
    [pApp.dtFmt setDateFormat:sInitDtFmt];
    return sTxt;
  }
  else {
    if(_pFatData == nil || index >= _pFatData.count)
      return @"";
      
    NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
    NSDateFormatter* dtFmt = pApp.dtFmt;
    if(index == 0)
      [dtFmt setDateFormat:@"MM/dd/yyyy"];
    else
      [dtFmt setDateFormat:@"MM/dd"];
      
    N_FatData *nFat = [_pFatData objectAtIndex:index];
    NSString* sTxt = [dtFmt stringFromDate:nFat.measDate];
    if(sTxt == nil)
      return @"";
      
    if(_pFatData.count > [_gViewFat getSwitchCount]) {
      if(index == 0) {
        [dtFmt setDateFormat:@"MM/dd/yyyy"];
        sTxt = [dtFmt stringFromDate:nFat.measDate];
      }
    }
    [pApp.dtFmt setDateFormat:sInitDtFmt];
    return sTxt;
  }
}

- (NSString *)barChart:(UIGraphView *)barChart textForBarAtIndex:(NSUInteger)index
{
  BOOL bShowWgt = barChart.nSetUnit < 6;

  CGFloat fDataVal = [self barChart:barChart valueForBarAtIndex:index];
  if(bShowWgt) {
    if(_pWgtData == nil || _pWgtData.count == 0)
      return @"0";
  }
  else {
    if(_pFatData == nil || _pFatData.count == 0)
      return @"0";
  }
  
  NSString* sDataVal = [NSString stringWithFormat:@"%.1f", fDataVal];
  if(!_bShowWgt)
    sDataVal = [sDataVal stringByAppendingString:@"%"];
   
  return sDataVal;
}

//move for fat view
- (void) moveOtherViewCtrl:(UIGraphView *)pView
{
  //CGFloat xCurtMovePos = pView.frame.origin.x;
  //CGFloat xPosOffset = xCurtMovePos - _xLastMovePos;
  
  CGRect frame = pView.frame;
  frame.size.height = _yHgtCtrl;
  if(pView == _gViewWgt) {
     _gViewFat.hidden = NO;
    frame.origin.x += _xScreenSize;
    //_lblMsg.text = [NSString stringWithFormat:@"Movind Fat: %.1f, %0.1f; %0.1f", pView.frame.origin.x, pView.frame.origin.y, xPosOffset];
    _gViewFat.frame = frame;
    
    //_gViewFat.layer.bounds = frame;
    //_gViewFat.layer.position = frame.origin;
    //_gViewFat. layer.cornerRadius=width/2;
  }
  else {
    _gViewWgt.hidden = NO;
    frame.origin.x -= _xScreenSize;
    //_lblMsg.text = [NSString stringWithFormat:@"Movind Wgt: %.1f, %0.1f; %0.1f", pView.frame.origin.x, pView.frame.origin.y, xPosOffset];
    _gViewWgt.frame = frame;
   // [_gViewWgt reloadData];
  }
  
  //if(_xLastMovePos == 0)
    //_xLastMovePos = xCurtMovePos;
}

- (void) moveOutForNextOne:(UIGraphView *)pView
{
    pView.hidden = YES;
    if(pView == _gViewWgt) {
      _bShowWgt = NO;
      _gViewWgt.hidden = YES;
      _gViewFat.hidden = NO;
      _gViewFat.center = _ptViewFat;
      _lblMsg.text = NSLocalizedString(@"Body Fat", nil);
      [_gViewFat reloadDataWithColor:DefaultColor];

    }
    else {
      _bShowWgt = YES;
      _lblMsg.text = NSLocalizedString(@"Body Weight", nil);
      _gViewFat.hidden = YES;
      _gViewWgt.hidden = NO;
      _gViewWgt.center = _ptViewWgt;
      [_gViewWgt reloadDataWithColor:DefaultColor];
    }
    [self chgDateRng:_scDateRng];
}

- (void) setWgtInitData
{
  if(_pWgtData.count == 0)
    return;
  
  N_WgtData* firstObj = (N_WgtData *)[_pWgtData firstObject];
  NSDate* dtStart = firstObj.iOsDateTime;
  _lastDatePos = [dtStart dateByAddingTimeInterval:0];//-_OneDaySeconds];
}

-(void) setFatInitData
{
  if(_pFatData.count == 0)
    return;
    
  N_FatData* firstObj = (N_FatData *)[_pFatData firstObject];
  NSDate* dtStart = firstObj.measDate;
  if(dtStart != nil)
    _lastDatePos = [dtStart dateByAddingTimeInterval:0];//-_OneDaySeconds];
  else
    _lastDatePos = [[NSDate date] dateByAddingTimeInterval:-365 * _OneDaySeconds];
}

//sync with svr
- (void) tapStartSync:(id)sender
{
  AppDelegate* pApp = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  if(![pApp isNetWorkConnAvailable]) {
    _lblMsg.text = NSLocalizedString(@"WAN network is not Aviable!", nil);
    _lblMsg.textColor = DefaultColor;
    AudioServicesPlaySystemSound(1112);
    return;
  }
  
   _lblMsg.text = NSLocalizedString(@"Begin Sync Data", nil);
  //_bMadeRcdMark = NO;
  _nSyncPos = 0;
  NSInteger nBodyId = pApp.m_bodyInfo.m_nBodyId;
  _nBodyId = nBodyId;
  
  //form exists data
  _pWgtData = [NSMutableArray arrayWithArray:[pApp loadWgtData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:YES last:NO]];
  NSUInteger nCount = _pWgtData.count;
  //[_dicSyncData removeAllObjects];
  
  NSString* sExistIds = @"(";
  for(NSUInteger i=0; i<nCount; i++) {
    N_WgtData* pData = [_pWgtData objectAtIndex:i];
    NSString* sKey = pData.measId.stringValue;
    //[_dicSyncData setObject:pData forKey:sKey];
    
    BOOL bALreadyInc = [sExistIds rangeOfString:sKey].location != NSNotFound;
    if(sKey.integerValue < 0 || bALreadyInc)
      continue;
    
    if(sExistIds.length > 1)
      sExistIds = [sExistIds stringByAppendingFormat:@",%@", sKey];
    else
      sExistIds = [sExistIds stringByAppendingFormat:@"%@", sKey];
  }
  sExistIds = [sExistIds stringByAppendingString:@")"];
  
  if(_progView == nil) {
    //CGRect frame = [[UIScreen mainScreen] bounds];
    //CGFloat W = frame.size.width;
    
    CGRect rt = _btnSyncData.frame;
    CGFloat yPos = rt.origin.y + 25;
    _progView = [[UIProgressView alloc] initWithFrame:CGRectMake(20, yPos, rt.origin.x-20, 10)];
    [self.view addSubview:_progView];
  }
  _progView.hidden = NO;
  _progView.progress = 0.0;
  
  if(_actView == nil) {
    CGRect rt = _btnSyncData.frame;
    _actView = [[UIActivityIndicatorView alloc] initWithFrame:rt];
    _actView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    _actView.hidesWhenStopped = YES;
    [self.view addSubview:_actView];
  }
  _btnSyncData.hidden = YES;
  //[NSThread detachNewThreadSelector:@selector(startActIndicator) toTarget:self withObject:nil];
  [_actView startAnimating];
  
  
  [self getWgtDataInfo:sExistIds];
}


-(void) getWgtDataInfo:(NSString*)sExistIds
{
  _lblMsg.text = NSLocalizedString(@"Sync WGT./Fat Data...", nil);
  _nSyncPos = 0;
  _nSyncCurrentPack = 0;
  _nSyncToatalPack = 0;
  _bSyncGetWgtReqst = YES;
  
  NSString* sUrl = [NSString stringWithFormat:@"Wgt?id=%ld&exist=%@&idx=%@" , (long)_nBodyId, sExistIds, @"1"];
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"DELETE" url:sUrl data:nil];
  request.timeoutInterval = 10.0;
  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] 
                         completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if(data == nil)
      return;

     
    // handle response
    NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    if(sRecv == nil) {
      [self stopSyncProcess:YES];
      return;
    }
    if(sRecv.length > 10) {
      //[self stopSyncProcess];
      _bSyncGetNotNeed = YES;
      [self getFatDataInfo];
      return;
    }
    else if(sRecv.length == 0) {
        _lblMsg.text = NSLocalizedString(@"APP Server can not connected!", nil);
      _lblMsg.textColor = DefaultColor;
       
      _nSyncToatalPack = -1;
      //[self stopShowSyncCtrld];
      _bSyncGetNotNeed = YES;
      [self getFatDataInfo];
      AudioServicesPlaySystemSound(1112);
      return;
    }
     
    _nSyncToatalPack = sRecv.integerValue;
    if(_nSyncToatalPack > 0) {
      _bSyncGetNotNeed = NO;
      [self requestWgtData];
      //[self syncSendHrateData];
    }
    else {
      //_lblMsg.text = @"Not need SYNC with Download";
      //[self performSelectorOnMainThread:@selector(noSyncDownloadTip:) withObject:@"Not need SYNC with Download" waitUntilDone:NO];
      //[NSThread sleepForTimeInterval:1.0];
      _bSyncGetNotNeed = YES;
      [self getFatDataInfo];
    }
   }];
  
  /*NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
   [task resume];*/
}

- (void) stopSyncProcess:(BOOL)bEnd
{
  if(bEnd) {
    dispatch_async(dispatch_get_main_queue(), ^{
      //[_netSession finishTasksAndInvalidate];
      AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      _pWgtData = [NSMutableArray arrayWithArray:[pApp loadWgtData:_nBodyId from:nil to:nil sort:YES last:NO]];
      _pFatData = [NSMutableArray arrayWithArray:[pApp loadFatData:_nBodyId from:nil to:nil sort:YES last:NO]];
    });
  }
  
  //[self performSelector:@selector(stopShowSyncCtrld) withObject:nil afterDelay:0.05];
  [self performSelectorOnMainThread:@selector(stopShowSyncCtrld) withObject:nil waitUntilDone:NO];
}

-(void) stopShowSyncCtrld
{  
  //dispatch_sync(dispatch_get_main_queue(), ^{
  NSString* sMsg = @"SYNC completed!";
  if(_bSyncGetNotNeed)
    sMsg = NSLocalizedString(@"Wgt./Fat Data Already SYNC!", nil);
  
  //dispatch_async(dispatch_get_main_queue(), ^{
  
  // computations 
  [_actView performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:NO];
  
  _btnSyncData.hidden = NO;
  if(_progView != nil)
    _progView.hidden = YES;
  
  _lblMsg.text = sMsg;
  //[_lblMsg performSelectorOnMainThread:@selector(setText:) withObject:sMsg waitUntilDone:YES];
  
  _bSyncEnd = YES;
  
   _scDateRng.selectedSegmentIndex = 0;
  [self setLastGoalWgt];
  [self chgDateRng:nil];
  
  if(_bSyncGetNotNeed)
    AudioServicesPlaySystemSound(1112);
}

- (void) requestWgtData {
  if(_nSyncPos >= _nSyncToatalPack) {
    _nSyncPos = 0;
    [self getFatDataInfo];
    return;
  }
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  NSString* sUrl = [NSString stringWithFormat:@"Wgt?id=%ld", (long)_nBodyId];
  NSDictionary *measData = @{
                             @"BodyId" : [NSString stringWithFormat:@"%ld", (long)_nBodyId],
                             @"hType" : [NSString stringWithFormat:@"1"],
                             @"_nSyncPos" : [NSString stringWithFormat:@"%ld", (long)_nSyncPos]
                             };
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:sUrl data:measData];
  request.timeoutInterval = 10.0;
  
  
  // 6.发送连接请求
  //[NSURLConnection connectionWithRequest:request delegate:self];
  NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
  [task resume];
}

//fat data sync
-(void) getFatDataInfo
{
  //[self stopSyncProcess:YES];
  //return;
  
   _lblMsg.text = NSLocalizedString(@"Sync FAT. Data...", nil);
  _nSyncPos = 0;
  _nSyncCurrentPack = 0;
  _nSyncToatalPack = 0;
   _bSyncGetWgtReqst = NO;
  //[_dicSyncData removeAllObjects];
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  _pFatData = [NSMutableArray arrayWithArray:[pApp loadFatData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:YES last:NO]];
  
  NSString* sExistIds = @"(";
  NSUInteger nCount = _pFatData.count;
  for(NSUInteger i=0; i<nCount; i++) {
    N_FatData* pData = [_pFatData objectAtIndex:i];
    NSString* sKey = pData.measId.stringValue;
    //[_dicSyncData setObject:pData forKey:sKey];
    
    BOOL bALreadyInc = [sExistIds rangeOfString:sKey].location != NSNotFound;
    if(sKey.integerValue < 0 || bALreadyInc)
      continue;
    
    if(sExistIds.length > 1)
      sExistIds = [sExistIds stringByAppendingFormat:@",%@", sKey];
    else
      sExistIds = [sExistIds stringByAppendingFormat:@"%@", sKey];
  }
  sExistIds = [sExistIds stringByAppendingString:@")"];
  
  NSString* sUrl = [NSString stringWithFormat:@"Wgt?id=%ld&exist=%@&idx=%@" , (long)_nBodyId, sExistIds, @"2"];
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"DELETE" url:sUrl data:nil];
  request.timeoutInterval = 10.0;
  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if(data == nil)
      return;
                           
    // handle response
    NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    if(sRecv.length > 10) {
      [self stopSyncProcess:YES];
      return;
    }
    else if(sRecv.length == 0) {
        _lblMsg.text = NSLocalizedString(@"APP Server can not connected!", nil);
      _lblMsg.textColor = DefaultColor;
                             
      _nSyncToatalPack = -1;
      [self stopSyncProcess:YES];
      AudioServicesPlaySystemSound(1112);
      return;
    }
                           
    _nSyncToatalPack = sRecv.integerValue;
    if(_nSyncToatalPack > 0) {
      _bSyncGetNotNeed = NO;
      [self requestFatData];
      //[self syncSendHrateData];
    }
    else {
      //_lblMsg.text = @"Not need SYNC with Download";
      //[self performSelectorOnMainThread:@selector(noSyncDownloadTip:) withObject:@"Not need SYNC with Download" waitUntilDone:NO];
      //[NSThread sleepForTimeInterval:1.0];
      _bSyncGetNotNeed = YES;
      [self stopSyncProcess:YES];
      //[self syncSendFatData];
    }
                         }];
  
  /*NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
   [task resume];*/
}

- (void) requestFatData {
  if(_nSyncPos >= _nSyncToatalPack) {
    _nSyncPos = 0;
    [self stopSyncProcess:YES];
    return;
  }
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  NSString* sUrl = [NSString stringWithFormat:@"Wgt?id=%ld", (long)_nBodyId];
  NSDictionary *measData = @{
                             @"BodyId" : [NSString stringWithFormat:@"%ld", (long)_nBodyId],
                             @"hType" : [NSString stringWithFormat:@"2"],
                             @"_nSyncPos" : [NSString stringWithFormat:@"%ld", (long)_nSyncPos]
                             };
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:sUrl data:measData];
  request.timeoutInterval = 10.0;
  
  
  // 6.发送连接请求
  //[NSURLConnection connectionWithRequest:request delegate:self];
  NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
  [task resume];

}

// do not need
- (void) syncSendWgtData
{
  /*_nSyncPos = 0;
  _nSyncCurrentPack = 0;
  _bSyncGetWgtReqst = NO;
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  _nSyncToatalPack = _pWgtData.count;
  
  _lblMsg.text = @"SYNC HRM Data (Upload)...";
  _lblMsg.textColor = [UIColor whiteColor];
  
  
  if(_nSyncToatalPack > 0) {
    // 4.设置请求体（请求参数）
    // 创建一个描述订单信息的JSON数据
    NSDictionary *measData = @{
                               @"BodyId" : [NSString stringWithFormat:@"%ld", (long)_nBodyId],
                               @"hType" : @"41"
                               };
    NSMutableURLRequest *request = [pApp requestWebApiRouter:@"POST" url:@"Msync" data:measData];
    //request.timeoutInterval = 5.0;
    
    
    // 6.发送连接请求
    //[NSURLConnection connectionWithRequest:request delegate:self];
    NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
    [task resume];
  }
  else {
    [self stopSyncProcess];
    AudioServicesPlaySystemSound(1112);
    return;
  }*/
}

- (void) showSyncProgress
{
  if(_nSyncToatalPack > 0) {
    if(_nSyncCurrentPack >= _nSyncToatalPack)
      _lblMsg.text = NSLocalizedString(@"Wait...", nil);
    else
      _lblMsg.text = [NSString stringWithFormat:@"SYNC %ld / %ld with %@...", (long)(_nSyncCurrentPack+1), (long)_nSyncToatalPack, (_bSyncGetWgtReqst?@"Download Wgt":@"Download Fat")]; //(long)(_nSyncPos+1)];
    CGFloat fProg = (CGFloat)(_nSyncCurrentPack+1) / _nSyncToatalPack;
    _progView.progress = fProg;
  }
}

- (void) storeSyncGetWgtData:(NSData*)wData
{
  if(_nSyncPos >= _nSyncToatalPack) {
    _nSyncPos = 0;
    [self getFatDataInfo];
    return;
  }
  [self performSelectorOnMainThread:@selector(showSyncProgress) withObject:nil waitUntilDone:NO];
  
  //NSString* sRecv = [[NSString alloc] initWithData:hData encoding:NSASCIIStringEncoding];
  
  NSError *e = nil;
  NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: wData options: NSJSONReadingMutableContainers error: &e];;
  for(NSDictionary *item in jsonArray) {
    //NSLog(@"Item: %@", item);
    NSNumber* nMeasId = [item objectForKey: @"MeasId"];
    NSString* sDate = [item objectForKey:@"MeasDate"];
    NSString* sScaleNo = [item objectForKey:@"ScaleNo"];

   
    NSNumber* nWgt = [item objectForKey:@"WgtValue"];
    NSNumber* nWu = [item objectForKey:@"MeasUnit"];
     
    [self storeSyncDownloadWgtData:nMeasId date:sDate scaleNo:sScaleNo wgt:nWgt un:nWu];
  }
  
  _nSyncPos++;
  [self requestWgtData];
}

- (void) storeSyncDownloadWgtData:(NSNumber*)nMeasId date:(NSString*)sDate scaleNo:(NSString*)sScaleNo wgt:(NSNumber*)nWgt un:(NSNumber*)nWu
{
  dispatch_sync(dispatch_get_main_queue(), ^{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp insertSyncWgtData:nMeasId dtScale:sDate sn:sScaleNo data:nWgt unit:nWu];
  });
}

- (void) storeSyncGetFatData:(NSData*)fData
{
  if(_nSyncPos >= _nSyncToatalPack) {
    _nSyncPos = 0;
    [self stopSyncProcess:YES];
    return;
  }
  [self performSelectorOnMainThread:@selector(showSyncProgress) withObject:nil waitUntilDone:NO];
  
  //NSString* sRecv = [[NSString alloc] initWithData:hData encoding:NSASCIIStringEncoding];
  
  NSError *e = nil;
  NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: fData options: NSJSONReadingMutableContainers error: &e];;
  for(NSDictionary *item in jsonArray) {
    //NSLog(@"Item: %@", item);
    NSNumber* nMeasId = [item objectForKey: @"MeasId"];
    NSString* sDate = [item objectForKey:@"MeasDate"];
    
    NSNumber* nFat = [item objectForKey:@"_dFatValue"];
    NSNumber* nWat = [item objectForKey:@"_dWatValue"];
    
    [self storeSyncDownloadFatData:nMeasId date:sDate fat:nFat wat:nWat];
  }
  
  _nSyncPos++;
  [self requestFatData];
}

- (void) storeSyncDownloadFatData:(NSNumber*)nMeasId date:(NSString*)sDate fat:(NSNumber*)nFat wat:(NSNumber*)nWat
{
  dispatch_sync(dispatch_get_main_queue(), ^{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp insertSyncFatData:nMeasId date:sDate fat:nFat wat:nWat];
  });
}

//delegate funcs
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
  //_lblMsg.text = error.description;
  if(error != nil) {
    _lblMsg.text = NSLocalizedString(@"APP Server Connection failed!", nil);
    _lblMsg.textColor = DefaultColor;
    [self stopSyncProcess:YES];
    AudioServicesPlaySystemSound(1112);
  }
}
    
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
  if (data == nil) {
    [_actView stopAnimating];
    _btnSyncData.hidden = NO;
    AudioServicesPlaySystemSound(1112);
    return;
  }
  
  //BOOL bShowProg = YES;
  if(_bSyncGetWgtReqst) {
    _nSyncCurrentPack++;
    [self storeSyncGetWgtData:data];
  }
  else {
    /*NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    sRecv = [sRecv substringWithRange: NSMakeRange(1, sRecv.length-2)];
    if([sRecv hasPrefix:@"Ready"]) {
      if([self sendWgtData])
        _nSyncCurrentPack++;
      
      _nSyncPos++;
    }
    else {
      [self stopSyncProcess];
    }*/
    _nSyncCurrentPack++;
    [self storeSyncGetFatData:data];
  }
  
  //if(bShowProg)
    //[self performSelectorOnMainThread:@selector(showSyncProgress) withObject:nil waitUntilDone:NO];
}

- (BOOL) sendWgtData
{
  /*AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSMutableArray* mutDate = _pHrtData;
  NSInteger nUpper = mutDate.count - 1;
  if(_nSyncPos > nUpper || nUpper < 0) {
    _nSyncPos = 0;
    [self stopShowSyncCtrld];
    return NO;
  }
  
  H_Rate* hrData = (H_Rate*)[mutDate objectAtIndex:_nSyncPos];
  if(hrData == nil)
    return NO;
  
  BOOL bEnd = _nSyncPos == nUpper;
  NSString* sHrateId = hrData.hRateId.stringValue;
  NSDate* dtStart = hrData.hEnterDate;
  NSDate* dtEnd = hrData.hEndDate;
  if(dtEnd == nil)
    dtEnd = dtStart;
  
  
  NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
  [pApp.dtFmt setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  
  NSDictionary *measData = @{
                             @"BodyId" : [NSString stringWithFormat:@"%ld", (long)_nBodyId],
                             @"m_nHrateId" : sHrateId,
                             @"m_dtStart" : [pApp.dtFmt stringFromDate:dtStart],
                             @"m_dtEnd" : [pApp.dtFmt stringFromDate:dtEnd],
                             @"m_nRateIdx" : @"-1", 
                             @"hType" : @"1"
                             };
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"POST" url:@"Wgt" data:measData];
  
  NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
  [task resume];
  
  [pApp.dtFmt setDateFormat:sInitDtFmt];
  
  if(bEnd) {
    _nSyncPos = 0;
    [self sendHrateRng];
  }*/
  
  return YES;
}

-(void) touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
  _lblMsg.text = NSLocalizedString(@"touch moving...", nil);
}

@end
